package com.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.constant.MessageConstant;
import com.result.Result;
import com.service.MemberService;
import com.service.ReportService;
import com.service.SetmealService;
import com.utils.DateUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    //统计分析 运营数据 导出
    @RequestMapping("/exportBusinessReport2")
    public void exportBusinessReport2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取运营数据
        Map<String, Object> ReportData = reportService.getBusinessReportData();
        //获取模板
        String realPath = request.getSession().getServletContext().getRealPath("/template/report_template.xlsx");
        //创建工作簿（模板路径）
        try// 写在try()里的对象，必须实现closable接口，try()cathc()中的finally
                (OutputStream os = response.getOutputStream();
                 XSSFWorkbook wk = new XSSFWorkbook(realPath);) {
            // 获取工作表
            XSSFSheet sht = wk.getSheetAt(0);
            //日期 坐标 （2，5）
            sht.getRow(2).getCell(5).setCellValue(ReportData.get("reportDate").toString());
            //新增会员数 坐标（4，5）
            sht.getRow(4).getCell(5).setCellValue(ReportData.get("todayNewMember").toString());
            //总会员数 坐标（4，7）
            sht.getRow(4).getCell(7).setCellValue(ReportData.get("totalMember").toString());
            //本周新增会员数 坐标（5，5）
            sht.getRow(5).getCell(5).setCellValue(ReportData.get("thisWeekNewMember").toString());
            //本月新增会员数 坐标（5，7）
            sht.getRow(5).getCell(7).setCellValue(ReportData.get("thisMonthNewMember").toString());
            //今日预约数 坐标（7，5）
            sht.getRow(7).getCell(5).setCellValue(ReportData.get("todayOrderNumber").toString());
            //今日到诊数 坐标（7，7）
            sht.getRow(7).getCell(7).setCellValue(ReportData.get("todayVisitsNumber").toString());
            //本周预约数 坐标（8，5）
            sht.getRow(8).getCell(5).setCellValue(ReportData.get("thisWeekOrderNumber").toString());
            //本周到诊数 坐标（8，7）
            sht.getRow(8).getCell(7).setCellValue(ReportData.get("thisWeekVisitsNumber").toString());
            //本月预约数 坐标（9，5）
            sht.getRow(9).getCell(5).setCellValue(ReportData.get("thisMonthOrderNumber").toString());
            //本月到诊数 坐标（9，7）
            sht.getRow(9).getCell(7).setCellValue(ReportData.get("thisMonthVisitsNumber").toString());
            //热门套餐
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) ReportData.get("hotSetmeal");
            int row = 12;
            for (Map<String, Object> setMealMap : hotSetmeal) {
                //套餐名称
                sht.getRow(row).getCell(4).setCellValue((String) setMealMap.get("name"));
                //预约数量
                sht.getRow(row).getCell(5).setCellValue((long) setMealMap.get("setmeal_count"));
                //占比
                String proportion = setMealMap.get("proportion").toString();
                String substring = proportion.substring(0, proportion.indexOf("%"));
                BigDecimal bigDecimal = new BigDecimal(substring);
                sht.getRow(row).getCell(6).setCellValue(bigDecimal.doubleValue() + "%");
                //备注
                sht.getRow(row).getCell(7).setCellValue((String) setMealMap.get("remark"));
                row++;
            }
            String filename = "运营统计数据报表.xlsx";
            // 解决下载的文件名 中文乱码
            filename = new String(filename.getBytes(), "ISO-8859-1");
            // 设置头信息，告诉浏览器，是带附件的，文件下载
            response.setHeader("Content-Disposition", "attachement;filename=" + filename);
            // 设置内容体的文件格式是excel
            response.setContentType("application/vnd.ms-excel");
            wk.write(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





    //统计分析 运营数据
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String, Object> businessReportData = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,businessReportData);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
    }

    //统计分析 套餐占比
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            List<Map<String, Object>> setmealReport = setmealService.getSetmealReport();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,setmealReport);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
    }


    //统计分析 会员数量
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        try {
            List<String> month = DateUtils.getLastYear4Month("YYYY.MM");
            System.out.println(month+"============================");
            List<Integer> memberCount = memberService.getMemberCount(month);
            Map<String,Object> map=new HashMap<>();
            map.put("months",month);
            map.put("memberCount",memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
    }

}
